package com.flying.scorer.service;

import com.flying.refdata.model.equity.EquityInfo;
import com.flying.refdata.model.equity.MarketData;
import com.flying.scorer.model.equity.EquityScore;
import com.flying.scorer.repository.equity.EquityScoreRepository;
import com.flying.scorer.score.ScoreException;
import com.flying.scorer.score.equity.EquityScorer;
import com.flying.utils.bean.BeanUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ScoreService {
    private static final Logger logger = LoggerFactory.getLogger(ScoreService.class);
    @Autowired
    private EquityScoreRepository repository;
    @Autowired
    private List<EquityScorer> scorers;

    private EquityScore saveEquityScore(EquityScore score) {
        if (score != null) {
            score = repository.save(score);
        }
        return score;
    }

    private List<EquityScore> saveEquityScore(Iterable<EquityScore> scores) {
        List<EquityScore> result = new ArrayList<>();
        if (scores == null) {
            return result;
        }
        for (EquityScore score : scores) {
            result.add(saveEquityScore(score));
        }
        return result;
    }

    public void score(Iterable<EquityInfo> infos, int beginDate, int endDate) {
        for (EquityInfo info : infos) score(info, beginDate, endDate);
    }

    public void score(EquityInfo info, int beginDate, int endDate) {
        List<MarketData> datas = repository.findUnScoredMarketDataByEquityInfoAndDateBetween(info, beginDate, endDate);
        for (MarketData md : datas) {
            List<EquityScore> scores = new ArrayList<>(scorers.size());
            for (EquityScorer scorer : scorers) {
                EquityScore score = new EquityScore();
                score.setScorerName(scorer.getInfo().getName());
                score.setEquityInfo(md.getEquityInfo());
                score.setDate(md.getDate());
                try {
                    score.setScore(scorer.score(md.getDate(), md.getEquityInfo()));
                    score.setSucceed(true);
                } catch (ScoreException se) {
                    score.setSucceed(false);
                    logger.warn("Ignore market data because of exception. market data:" + BeanUtil.describe(md), se);
                }
                scores.add(score);
            }
            saveEquityScore(scores);
        }
    }
}